package com.wusiwei.service.impl;

import com.wusiwei.entity.Invoice;
import com.wusiwei.entity.Order;
import com.wusiwei.entity.OrderItem;
import com.wusiwei.entity.Receipt;
import com.wusiwei.mapper.InvoiceMapper;
import com.wusiwei.mapper.OrderMapper;
import com.wusiwei.mapper.ReceiptMapper;
import com.wusiwei.service.OrderService;
import com.wusiwei.vo.OrderStatistics;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单服务实现类
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {

    private final OrderMapper orderMapper;
    private final ReceiptMapper receiptMapper;
    private final InvoiceMapper invoiceMapper;

    @Override
    public List<Order> getAllOrders() {
        // 获取所有订单基本信息
        List<Order> orders = orderMapper.selectList(null);

        // 为每个订单加载明细数据
        if (orders != null && !orders.isEmpty()) {
            for (Order order : orders) {
                List<OrderItem> items = orderMapper.selectOrderItems(order.getId());
                order.setItems(items);
            }
        }

        return orders;
    }

//    @Override
//    public List<Order> getOrderList(OrderQueryDTO queryDTO) {
//        Map<String, Object> params = new HashMap<>();
//        if (queryDTO != null) {
//            params.put("orderNumber", queryDTO.getOrderNumber());
//            params.put("supplierName", queryDTO.getSupplierName());
//            params.put("status", queryDTO.getStatus());
//            params.put("startDate", queryDTO.getStartDate());
//            params.put("endDate", queryDTO.getEndDate());
//        }
//
//        return orderMapper.selectList(params);
//    }

    @Override
    public Order getOrderById(Long id) {
        // 查询订单基本信息
        Order order = orderMapper.selectById(id);
        if (order != null) {
            // 查询订单明细
            order.setItems(orderMapper.selectOrderItems(id));
        }
        return order;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createOrder(Order order) {
        // 生成订单号
        if (order.getOrderNumber() == null || order.getOrderNumber().isEmpty() || "系统自动生成".equals(order.getOrderNumber())) {
            order.setOrderNumber(generateOrderNumber());
        }

        // 保存订单主信息
        orderMapper.insert(order);

        // 保存订单明细
        if (order.getItems() != null && !order.getItems().isEmpty()) {
            order.getItems().forEach(item -> {
                item.setOrderId(order.getId());
                orderMapper.insertOrderItem(item);
            });
        }

        return true;
    }

    /**
     * 生成订单号
     * 格式：PO + 年月日 + 四位序号
     * 例如：PO2023052300001
     */
    private String generateOrderNumber() {
        // 生成日期前缀
        String prefix = "PO" + java.time.LocalDate.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd"));

        // 获取当天最大订单号
        String likePattern = prefix + "%";
        String maxOrderNumber = orderMapper.selectMaxOrderNumberByPrefix(likePattern);

        int sequence = 1;
        if (maxOrderNumber != null && maxOrderNumber.length() > prefix.length()) {
            try {
                String sequenceStr = maxOrderNumber.substring(prefix.length());
                sequence = Integer.parseInt(sequenceStr) + 1;
            } catch (NumberFormatException e) {
                log.error("解析订单号序列失败: {}", maxOrderNumber, e);
            }
        }

        // 生成新的订单号，四位数字，不足前补0
        return prefix + String.format("%04d", sequence);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOrder(Long id, Order order) {
        log.info("开始更新订单, 订单ID: {}, 订单基本信息: {}", id, order);

        // 检查订单是否存在且状态是否为"待收货"
        Order existingOrder = orderMapper.selectById(id);
        if (existingOrder == null) {
            log.error("订单不存在, ID: {}", id);
            throw new IllegalArgumentException("订单不存在");
        }

        if (!"待收货".equals(existingOrder.getStatus())) {
            log.error("只有待收货状态的订单才能更新, 当前状态: {}", existingOrder.getStatus());
            throw new IllegalStateException("只有待收货状态的订单才能编辑");
        }

        // 更新订单基本信息
        order.setId(id);
        orderMapper.updateById(order);
        log.info("订单基本信息更新成功");

        // 获取原有的订单明细
        List<OrderItem> oldItems = orderMapper.selectOrderItems(id);
        log.info("获取到原有订单明细: {}", oldItems);

        // 先删除旧的订单明细
        int deletedCount = orderMapper.deleteOrderItems(id);
        log.info("删除原有订单明细, 数量: {}", deletedCount);

        // 保存新的订单明细
        if (order.getItems() != null && !order.getItems().isEmpty()) {
            log.info("准备插入新的订单明细, 数量: {}", order.getItems().size());
            order.getItems().forEach(item -> {
                item.setOrderId(id);
                log.info("插入订单明细: {}", item);
                orderMapper.insertOrderItem(item);
            });
        } else {
            log.warn("更新订单时未提供任何明细项, 订单ID: {}", id);
        }

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteOrder(Long id) {
        // 检查订单是否存在且状态是否为"待收货"
        Order existingOrder = orderMapper.selectById(id);
        if (existingOrder == null) {
            log.error("订单不存在, ID: {}", id);
            throw new IllegalArgumentException("订单不存在");
        }

        if (!"待收货".equals(existingOrder.getStatus())) {
            log.error("只有待收货状态的订单才能删除, 当前状态: {}", existingOrder.getStatus());
            throw new IllegalStateException("只有待收货状态的订单才能删除");
        }

        // 逻辑删除，将删除标记设为1
        return orderMapper.updateDeleted(id, 1) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDeleteOrders(List<Long> ids) {
        // 检查所有订单是否都是"待收货"状态
        for (Long id : ids) {
            Order existingOrder = orderMapper.selectById(id);
            if (existingOrder == null) {
                log.error("订单不存在, ID: {}", id);
                throw new IllegalArgumentException("订单不存在, ID: " + id);
            }

            if (!"待收货".equals(existingOrder.getStatus())) {
                log.error("只有待收货状态的订单才能删除, 订单ID: {}, 当前状态: {}", id, existingOrder.getStatus());
                throw new IllegalStateException("只有待收货状态的订单才能删除, 订单ID: " + id);
            }
        }

        // 批量逻辑删除
        return orderMapper.batchUpdateDeleted(ids, 1) > 0;
    }

    @Override
    public Object getOrderPage(int pageNum, int pageSize, String orderNumber,
                               String supplierName, String status,
                               String startDate, String endDate) {
        // 构建查询参数
        Map<String, Object> params = new HashMap<>();
        params.put("pageNum", pageNum);
        params.put("pageSize", pageSize);
        params.put("orderNumber", orderNumber);
        params.put("supplierName", supplierName);
        params.put("status", status);

        // 只有当日期不为null且不为空字符串时才添加到参数中
        if (startDate != null && !startDate.isEmpty()) {
            params.put("startDate", startDate);
        }
        if (endDate != null && !endDate.isEmpty()) {
            params.put("endDate", endDate);
        }

        // 计算分页偏移量
        int offset = (pageNum - 1) * pageSize;
        params.put("offset", offset);

        // 查询总数
        long total = orderMapper.countOrders(params);

        // 分页查询
        List<Order> orders = orderMapper.selectOrderPage(params);

        // 为每个订单加载明细数据
        if (orders != null && !orders.isEmpty()) {
            for (Order order : orders) {
                List<OrderItem> items = orderMapper.selectOrderItems(order.getId());
                order.setItems(items);
            }
        }

        // 构建分页结果
        Map<String, Object> result = new HashMap<>();
        result.put("total", total);
        result.put("records", orders);
        result.put("size", pageSize);
        result.put("current", pageNum);
        result.put("pages", (total + pageSize - 1) / pageSize);

        return result;
    }

    @Override
    public OrderStatistics getOrderStatusStatistics() {
        return orderMapper.selectOrderStatusStats();
    }

    @Override
    public byte[] exportOrders(String orderNumber, String supplierName, String status, String startDate, String endDate) {
        log.info("导出订单数据，条件：订单号={}, 供应商={}, 状态={}, 开始日期={}, 结束日期={}",
                orderNumber, supplierName, status, startDate, endDate);

        // 构建查询参数
        Map<String, Object> params = new HashMap<>();
        // 只有在参数非空且有值时才添加到查询条件中
        if (orderNumber != null && !orderNumber.trim().isEmpty()) {
            params.put("orderNumber", orderNumber);
        }
        if (supplierName != null && !supplierName.trim().isEmpty()) {
            params.put("supplierName", supplierName);
        }
        if (status != null && !status.trim().isEmpty()) {
            params.put("status", status);
        }
        if (startDate != null && !startDate.trim().isEmpty()) {
            params.put("startDate", startDate);
        }
        if (endDate != null && !endDate.trim().isEmpty()) {
            params.put("endDate", endDate);
        }

        // 查询订单数据 - 没有条件时会查询所有订单
        List<Order> orders = orderMapper.selectList(params);
        log.info("查询到 {} 条符合条件的订单数据", orders.size());

        // 导出Excel
        try {
            // 创建工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("订单数据");

            // 创建表头
            Row headerRow = sheet.createRow(0);
            String[] headers = {"订单编号", "供应商", "订单金额", "状态", "创建时间"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 填充数据
            int rowNum = 1;
            for (Order order : orders) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(order.getOrderNumber());
                row.createCell(1).setCellValue(order.getSupplierName());
                row.createCell(2).setCellValue(order.getTotalAmount() != null ? order.getTotalAmount().doubleValue() : 0);
                row.createCell(3).setCellValue(order.getStatus());
                row.createCell(4).setCellValue(order.getCreateTime() != null ? order.getCreateTime().toString() : "");
            }

            // 调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }

            // 转换为字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            workbook.close();

            byte[] fileContent = outputStream.toByteArray();
            log.info("成功生成Excel文件，大小: {} 字节", fileContent.length);
            return fileContent;
        } catch (IOException e) {
            log.error("导出订单Excel出错", e);
            throw new RuntimeException("导出订单失败", e);
        }
    }

    @Override
    public List<Order> findBySupplierAndAmount(String supplierName, BigDecimal targetAmount,
                                               BigDecimal minAmount, BigDecimal maxAmount) {
        return orderMapper.findBySupplierAndAmount(supplierName, minAmount, maxAmount);
    }

    @Override
    public List<Order> findBySimilarSupplierAndAmount(String supplierName, BigDecimal targetAmount,
                                                      BigDecimal minAmount, BigDecimal maxAmount) {
        log.info("根据模糊供应商名称和金额范围查询订单，供应商: {}, 目标金额: {}, 范围: {} - {}",
                supplierName, targetAmount, minAmount, maxAmount);

        // 如果供应商名称为空则返回空列表
        if (supplierName == null || supplierName.trim().isEmpty()) {
            return Collections.emptyList();
        }

        // 使用模糊查询在mapper中查找供应商名称相似的订单
        return orderMapper.findBySimilarSupplierAndAmount(supplierName, minAmount, maxAmount);
    }

    @Override
    public Order findById(Long id) {
        log.info("根据ID查找订单: {}", id);
        if (id == null) {
            return null;
        }
        return orderMapper.selectById(id);
    }

//    @Override
//    public BigDecimal getTotalOrderAmount() {
//        try {
//            return orderMapper.selectTotalOrderAmount();
//        } catch (Exception e) {
//            log.error("获取订单总金额失败", e);
//            return BigDecimal.ZERO;
//        }
//    }

    /**
     * 获取订单总金额
     *
     * @return 订单总金额
     */
    @Override
    public BigDecimal getTotalAmount() {
        log.info("获取订单总金额");
        try {
            return orderMapper.getTotalOrderAmount();
        } catch (Exception e) {
            log.error("获取订单总金额失败", e);
            return BigDecimal.ZERO;
        }
    }

    /**
     * 获取订单总金额统计
     *
     * @return 金额统计
     */
    @Override
    public Map<String, Object> getTotalAmountStats() {
        log.info("获取订单总金额统计");
        try {
            Map<String, Object> stats = new HashMap<>();

            // 获取总金额
            BigDecimal totalAmount = getTotalAmount();
            stats.put("totalAmount", totalAmount);

            // 获取本月订单金额
            BigDecimal currentMonthAmount = orderMapper.getCurrentMonthOrderAmount();
            stats.put("currentMonthAmount", currentMonthAmount);

            // 计算同比增长率（与上月相比）
            BigDecimal lastMonthAmount = orderMapper.getLastMonthOrderAmount();
            if (lastMonthAmount != null && lastMonthAmount.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal growthRate = currentMonthAmount.subtract(lastMonthAmount)
                        .divide(lastMonthAmount, 4, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal("100"));
                stats.put("monthGrowthRate", growthRate);
            } else {
                stats.put("monthGrowthRate", BigDecimal.ZERO);
            }

            // 计算平均订单金额
            int totalCount = countTotal();
            if (totalCount > 0) {
                BigDecimal averageAmount = totalAmount.divide(BigDecimal.valueOf(totalCount), 2, RoundingMode.HALF_UP);
                stats.put("averageAmount", averageAmount);
            } else {
                stats.put("averageAmount", BigDecimal.ZERO);
            }

            return stats;
        } catch (Exception e) {
            log.error("获取订单总金额统计失败", e);
            return new HashMap<>();
        }
    }

    /**
     * 统计订单总数
     *
     * @return 订单总数
     */
    @Override
    public int countTotal() {
        log.info("统计订单总数");
        try {
            return orderMapper.countTotal();
        } catch (Exception e) {
            log.error("统计订单总数失败", e);
            return 0;
        }
    }

    /**
     * 按状态统计订单
     *
     * @return 状态统计结果
     */
    @Override
    public List<Map<String, Object>> countByStatus() {
        log.info("按状态统计订单");
        try {
            return orderMapper.countByStatus();
        } catch (Exception e) {
            log.error("按状态统计订单失败", e);
            return new ArrayList<>();
        }
    }

    /**
     * 按供应商统计订单
     *
     * @return 供应商统计结果
     */
    @Override
    public List<Map<String, Object>> countBySupplier() {
        log.info("按供应商统计订单");
        try {
            return orderMapper.countBySupplier();
        } catch (Exception e) {
            log.error("按供应商统计订单失败", e);
            return new ArrayList<>();
        }
    }

//    /**
//     * 获取订单趋势
//     *
//     * @return 订单趋势数据
//     */
//    @Override
//    public List<Map<String, Object>> getOrderTrend() {
//        log.info("获取订单趋势");
//        try {
//            // 获取最近6个月的订单数据
//            return orderMapper.getOrderTrendByMonth(6);
//        } catch (Exception e) {
//            log.error("获取订单趋势失败", e);
//            return new ArrayList<>();
//        }
//    }

    /**
     * 获取当月订单数量
     *
     * @return 当月订单数量
     */
    @Override
    public int getCurrentMonthOrderCount() {
        log.info("获取当月订单数量");
        try {
            return orderMapper.getCurrentMonthOrderCount();
        } catch (Exception e) {
            log.error("获取当月订单数量失败", e);
            return 0;
        }
    }

    /**
     * 获取月度订单趋势
     *
     * @param year 年份
     * @return 月度趋势数据
     */
    @Override
    public List<Map<String, Object>> getMonthlyOrderTrend(Integer year) {
        log.info("获取月度订单趋势, 年份: {}", year);
        try {
            // 如果未指定年份，使用当前年份
            if (year == null) {
                year = java.time.LocalDate.now().getYear();
                log.info("未指定年份，使用当前年份: {}", year);
            }

            // 检查指定年份有多少订单数据
            int orderCount = orderMapper.countOrdersByYear(year);
            log.info("{}年的订单数量: {}", year, orderCount);

            // 查询订单月度趋势
            List<Map<String, Object>> result = orderMapper.getMonthlyOrderTrend(year);

            // 打印每个月的数据
            if (result != null && !result.isEmpty()) {
                log.info("获取到{}年月度趋势数据, 共{}条记录:", year, result.size());
                for (Map<String, Object> monthData : result) {
                    log.info("月份: {}, 数量: {}, 金额: {}",
                            monthData.get("month"),
                            monthData.get("count"),
                            monthData.get("totalAmount"));
                }

                // 确保返回的数据是按月份排序的
                result.sort((a, b) -> {
                    String monthA = String.valueOf(a.get("month"));
                    String monthB = String.valueOf(b.get("month"));
                    return monthA.compareTo(monthB);
                });
            } else {
                log.warn("{}年未查询到任何月度数据，返回空列表", year);
                result = new ArrayList<>();
            }

            return result;
        } catch (Exception e) {
            log.error("获取月度订单趋势失败: {}", e.getMessage(), e);
            // 返回空列表而不是抛出异常
            return new ArrayList<>();
        }
    }
//
//    @Override
//    public List<OrderStatistics.MonthlyAmount> getMonthlyOrderAmounts() {
//        return orderMapper.selectMonthlyOrderAmounts();
//    }

//    @Override
//    public Map<String, Integer> getStatusCount() {
//        return orderMapper.selectStatusCount();
//    }

    @Override
    public Object getOrderRelatedDocuments(Long orderId) {
        Map<String, Object> result = new HashMap<>();

        // 获取关联的收货单
        List<Receipt> receipts = receiptMapper.getReceiptsByOrderId(orderId);
        List<Map<String, Object>> receiptList = receipts.stream()
                .map(receipt -> {
                    Map<String, Object> receiptMap = new HashMap<>();
                    receiptMap.put("id", receipt.getId());
                    receiptMap.put("number", receipt.getReceiptNumber());
                    receiptMap.put("status", receipt.getStatus());
                    receiptMap.put("type", "收货单");
                    receiptMap.put("url", "/dashboard/receipt-detail/" + receipt.getId());
                    return receiptMap;
                })
                .collect(Collectors.toList());

        // 获取关联的发票
        List<Invoice> invoices = invoiceMapper.getInvoicesByOrderId(orderId);
        List<Map<String, Object>> invoiceList = invoices.stream()
                .map(invoice -> {
                    Map<String, Object> invoiceMap = new HashMap<>();
                    invoiceMap.put("id", invoice.getId());
                    invoiceMap.put("number", invoice.getInvoiceNumber());
                    invoiceMap.put("status", "已开票"); // 直接使用固定状态
                    invoiceMap.put("type", "发票");
                    invoiceMap.put("url", "/dashboard/invoice-detail/" + invoice.getId());
                    return invoiceMap;
                })
                .collect(Collectors.toList());

        result.put("receipts", receiptList);
        result.put("invoices", invoiceList);

        return result;
    }

    /**
     * 统计指定年份的订单数量
     *
     * @param year 年份
     * @return 订单数量
     */
    @Override
    public int countOrdersByYear(Integer year) {
        log.info("统计{}年的订单数量", year);
        try {
            return orderMapper.countOrdersByYear(year);
        } catch (Exception e) {
            log.error("统计{}年的订单数量失败", year, e);
            return 0;
        }
    }

    @Override
    public Order findByOrderNumber(String orderNumber) {
        if (orderNumber == null || orderNumber.trim().isEmpty()) {
            return null;
        }

        // 使用条件查询订单
        Map<String, Object> params = new HashMap<>();
        params.put("orderNumber", orderNumber);
        List<Order> orders = orderMapper.selectList(params);

        // 如果找到订单，加载订单明细
        if (orders != null && !orders.isEmpty()) {
            Order order = orders.get(0);
            List<OrderItem> items = orderMapper.selectOrderItems(order.getId());
            order.setItems(items);
            return order;
        }

        return null;
    }

    @Override
    public List<OrderItem> getOrderItems(Long orderId) {
        if (orderId == null) {
            return Collections.emptyList();
        }
        return orderMapper.selectOrderItems(orderId);
    }
} 